package com.rex.saas.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class EmailSender163 {
    private static volatile EmailSender163 instance;

    private Session session;

    private static final String USERNAME = "marketing@rexense.com";
    private static final String PASSWORD = "jWCV7qC6c2qUnw8s";

    private EmailSender163() throws GeneralSecurityException {
        configureSession();
    }

    private void configureSession() throws GeneralSecurityException {
        //配置邮件属性
        Properties props = new Properties();
        //开启debug模式
        props.setProperty("mail.debug", "false");
        //开启smtp认证
        props.setProperty("mail.smtp.auth", "true");
        //网易企业邮箱（smtphz.qiye.163.com）ssl加密端口
        props.setProperty("mail.smtp.port", "994");
        //关闭tls
        props.setProperty("mail.smtp.starttls.enable", "false");
        props.setProperty("mail.smtp.starttls.required", "false");
        //设置传输协议为smtp
        props.setProperty("mail.transport.protocol","smtp");
        //开启ssl加密
        props.setProperty("mail.smtp.ssl.enable", "true");
        MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
        sslSocketFactory.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
        //网易企业邮箱host
        props.setProperty("mail.smtp.host","smtphz.qiye.163.com");
        session = Session.getInstance(props);
        session.setDebug(false);
    }

    public static EmailSender163 getInstance() throws GeneralSecurityException {
        if (instance == null) {
            synchronized (EmailSenderQQ.class) {
                if (instance == null) {
                    instance = new EmailSender163();
                }
            }
        }
        return instance;
    }

    public void sendEmail(String recipient, String subject, String content) throws MessagingException {
        MimeMessage mimeMessage = new MimeMessage(session);
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        helper.setFrom(USERNAME);
        helper.setTo(recipient);
        helper.setText(content, true);
        helper.setSubject(subject);
        //发送邮件
        Transport transport = session.getTransport();
        transport.connect(USERNAME,PASSWORD);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    }

    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        EmailSender163 emailSender = EmailSender163.getInstance();
        emailSender.sendEmail("547203131@qq.com", "Test Email", "163发送SSL邮箱.");
    }
}
